﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Windows.Forms;
using BusinessObjects.Constants;
using BusinessServices;
using CarLeaseManageSystem.Properties;
using Core.Utilities;
using DataEntities;

namespace CarLeaseManageSystem
{
    public partial class FormWeiZhangMana : Form
    {
        private readonly KeHuService _keHuService;
        private readonly WeiZhangService _weiZhangService;
        private readonly ChuZuService _chuZuService;
        private readonly List<KeHuInfo> _keHuInfoCache;

        public FormWeiZhangMana()
        {
            _keHuService = new KeHuService();
            _chuZuService = new ChuZuService();
            _weiZhangService = new WeiZhangService();
            _keHuInfoCache = new List<KeHuInfo>();
            InitializeComponent();
        }

        private void FormWeiZhangMana_Load(object sender, EventArgs e)
        {
            comBoxArea.SelectedIndex = 2;
        }

        //过滤客户
        private void comBoxArea_SelectedIndexChanged(object sender, EventArgs e)
        {
            var index = comBoxArea.SelectedIndex;
            List<KeHuInfo> keHuInfo;

            switch (index)
            {
                case 0:
                    keHuInfo = _keHuService.GetWeiZhangKeHuInfo();
                    break;
                case 1:
                    keHuInfo = _keHuService.GetNeverWeiZhangKeHuInfo();
                    break;
                default:
                    keHuInfo = _keHuService.GetAllWeiZhangeKeHuInfo();
                    break;
            }

            UpdateKeHuListView(keHuInfo);
        }

        //更新客户列表控件
        private void UpdateKeHuListView(List<KeHuInfo> keHuInfo)
        {
            listViewExist.Items.Clear();
            _keHuInfoCache.Clear();
            keHuInfo.ForEach(userInfo =>
                                 {
                                     var name = string.Format("{0}({1})", userInfo.sName, userInfo.sIdCard.Substring(14, 4));
                                     var newItems = new ListViewItem
                                     {
                                         Tag = userInfo.iKeHuId,
                                         Text = name
                                     };
                                     listViewExist.Items.Add(newItems);
                                     _keHuInfoCache.Add(userInfo);
                                 });
        }

        //当切换客户时切换违章信息
        ListViewItemSelectionChangedEventArgs e1;
        private void listViewExist_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (!e.IsSelected)
            {
                return;
            }
            e1 = e;
            ResetControlsWhenCreate(false);
            var keHuId = (int)e.Item.Tag;
            var weiZhangInfo = _weiZhangService.GetWeiZhangInfoByKeHuId(keHuId);
            var obj = weiZhangInfo.Select(wei => new
            {
                出租单 = wei.iCZDId,
                客编 = wei.iKeHuId,
                客户 = wei.KeHuInfo.sName,
                车编 = wei.iCarid,
                车辆 = string.Format("{0}({1})", wei.CarInfo.sCType, wei.CarInfo.sCPId),
                地点 = wei.sWZAddr,
                内容 = wei.sWZDetail,
                罚金 = wei.dWZJE,
                日期 = wei.tWZDate,
                客照 = wei.KeHuInfo.mPhoto,
                车照 = wei.CarInfo.mCPhoto,
                状态 = wei.bWZZF ? "已处理" : "未处理"
            });
            if (weiZhangInfo.Count == 0)
            {
                ClearDataBindings();
                return;
            }
            BindingDataToControls(obj);
        }

        //绑定数据到控件
        private void BindingDataToControls<AT0>(IEnumerable<AT0> obj)
        {
            ClearDataBindings();
            bindingSource.DataSource = obj.AsQueryable();
            bindingNavigator1.BindingSource = bindingSource;
            labStatus.DataBindings.Add(new Binding("Text", bindingSource, "状态"));
            labWZInfo.DataBindings.Add(new Binding("Tag", bindingSource, "出租单"));
            txtName.DataBindings.Add(new Binding("Tag", bindingSource, "客编"));
            txtName.DataBindings.Add(new Binding("Text", bindingSource, "客户"));
            txtCar.DataBindings.Add(new Binding("Tag", bindingSource, "车编"));
            txtCar.DataBindings.Add(new Binding("Text", bindingSource, "车辆"));
            txtAddr.DataBindings.Add(new Binding("Text", bindingSource, "地点"));
            txtCont.DataBindings.Add(new Binding("Text", bindingSource, "内容"));
            numMoney.DataBindings.Add(new Binding("Value", bindingSource, "罚金"));
            dateTime.DataBindings.Add(new Binding("Value", bindingSource, "日期"));
            Binding bindKeHu = new Binding("Image", bindingSource, "客照");
            bindKeHu.Format += new ConvertEventHandler(ConvertUserImage);
            pictKeHu.DataBindings.Add(bindKeHu);

            Binding bindCar = new Binding("Image", bindingSource, "车照");
            bindCar.Format += new ConvertEventHandler(ConvertCarImage);
            pictBoxCar.DataBindings.Add(bindCar);
        }

        //转换汽车照片二进制数据为图片
        private void ConvertCarImage(object sender, ConvertEventArgs e)
        {
            e.Value = ((Binary)e.Value).ToImage().MergeImg(pictKeHu.Image);
        }

        //转换客户照片二进制数据为图片
        private void ConvertUserImage(object sender, ConvertEventArgs e)
        {
            e.Value = ((Binary)e.Value).ToImage().Resize(50, 60);
        }

        //清除控件数据绑定
        private void ClearDataBindings()
        {
            bindingSource = new BindingSource();
            labStatus.DataBindings.Clear();
            labWZInfo.DataBindings.Clear();
            txtName.DataBindings.Clear();
            txtCont.DataBindings.Clear();
            txtCar.DataBindings.Clear();
            txtAddr.DataBindings.Clear();
            numMoney.DataBindings.Clear();
            dateTime.DataBindings.Clear();
            pictBoxCar.DataBindings.Clear();
            pictKeHu.DataBindings.Clear();
            labWZInfo.DataBindings.Clear();
            bindingNavigator1.BindingSource = null;
            txtName.Text = string.Empty;
            txtCar.Text = string.Empty;
            txtAddr.Text = string.Empty;
            txtCont.Text = string.Empty;
            numMoney.Value = default(decimal);
            dateTime.Value = DateTime.Now;
            pictBoxCar.Image = Resources.car2;
        }

        //检索客户
        private void txtBoxSearName_TextChanged(object sender, EventArgs e)
        {
            listViewExist.Items.Clear();
            var key = txtBoxSearName.Text;
            foreach (KeHuInfo keHuInfo in _keHuInfoCache.Where(keHu => keHu.sName.Contains(key) || keHu.sIdCard.Contains(key)))
            {
                var newItems = new ListViewItem
                {
                    Tag = keHuInfo.iKeHuId,
                    Text = string.Format("{0}({1})", keHuInfo.sName, keHuInfo.sIdCard.Substring(14, 4))
                };
                listViewExist.Items.Add(newItems);
            }
        }

        //获取出租信息,并将值绑定到相应控件
        private void BindChuZuInfo()
        {
            var keHuId = (int)listViewExist.SelectedItems[0].Tag;
            var chuZuInfo = _chuZuService.GetActiveChuZuInfo().Where(o => o.iKeHuId == keHuId);
            if (chuZuInfo.Count() == 0)
            {
                MessageBox.Show(WeiZhangConstant.CreateError, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var obj = chuZuInfo.Select(zu => new
            {
                出租单 = zu.iCZDId,
                客编 = zu.iKeHuId,
                客户 = zu.KeHuInfo.sName,
                车编 = zu.iCarid,
                车辆 = string.Format("{0}({1})", zu.CarInfo.sCType, zu.CarInfo.sCPId),
                地点 = string.Empty,
                内容 = string.Empty,
                罚金 = default(decimal),
                日期 = DateTime.Now,
                客照 = zu.KeHuInfo.mPhoto,
                车照 = zu.CarInfo.mCPhoto,
                状态 = "新建"
            });
            ResetControlsWhenCreate(true);
            BindingDataToControls(obj);
        }

        //新建或保存违章信息
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (listViewExist.SelectedItems.Count == 0)
            {
                MessageBox.Show(WeiZhangConstant.AppointUser, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (btnOk.Text == "新建")
            {
                BindChuZuInfo();
                return;
            }
            if (btnOk.Text == "保存")
            {
                var newWeiZhangInfo = new WeiZhangInfo
                {
                    iCZDId = (int)labWZInfo.Tag,
                    iKeHuId = (int)txtName.Tag,
                    iCarid = (int)txtCar.Tag,
                    sWZAddr = txtAddr.Text,
                    sWZDetail = txtCont.Text,
                    dWZJE = (double)numMoney.Value,
                    tWZDate = dateTime.Value
                };
                newWeiZhangInfo = _weiZhangService.Add(newWeiZhangInfo);
                if (newWeiZhangInfo.iWZDId > 0)
                {
                    MessageBox.Show(WeiZhangConstant.AddSucceed, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ResetControlsWhenCreate(false);
                    listViewExist_ItemSelectionChanged(sender, e1);
                    comBoxArea_SelectedIndexChanged(sender, e);
                }
                else
                {
                    MessageBox.Show(WeiZhangConstant.AddFailed, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        //改变控件可用状态
        private void ResetControlsWhenCreate(bool isCreate)
        {
            numMoney.Enabled = dateTime.Enabled = isCreate;
            txtAddr.ReadOnly = txtCont.ReadOnly = !isCreate;
            btnOk.Text = isCreate ? "保存" : "新建";
        }
    }
}
